<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Route;

class PermissionAccess
{

    public function __construct(Route $route)
    {
        $this->route = $route;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 当前控制器
        $action = $this->route->getActionName();
        $user   = $request->user();

         // 判断当前请求是否为开放权限
        if ($user->isAdmin() || in_array($action, config('open_permissions'))) {
            return $next($request);
        }

        // 控制器和标签的对应关系
        $permissions = config('compile_permissions'); 
        // 系统没有添加该标签对应关系
        if (!isset($permissions[$action])) {
            if ($request->ajax()) {
                return response('权限错误，请联系管理员。', 500);
            }
            return abort(500, '权限错误，请联系管理员。');
        }
        // 判断当前用户是否有权限访问该内容
        if (!$user->can($permissions[$action])) {
            if ($request->ajax()) {
                return response('您没有权限访问该内容。', 403);
            }
            return abort(403, '您没有权限访问该内容。');
        }

        return $next($request);
    }
}
